package com.wenyu.wenyuyuedu.activity.circle;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.wenyu.wenyuyuedu.R;
import com.wenyu.wenyuyuedu.activity.LoginActivity;
import com.wenyu.wenyuyuedu.activity.personage.Help_FeedBack_Activity;
import com.wenyu.wenyuyuedu.bean.circle.CircleDetailBean;
import com.wenyu.wenyuyuedu.bean.circle.JoinCircleBean;
import com.wenyu.wenyuyuedu.fragment.circlefragment.FindAll_Invitation_Fragment;
import com.wenyu.wenyuyuedu.global.ApiWrapper;
import com.wenyu.wenyuyuedu.server.circle.JoinCircleServer;
import com.wenyu.wenyuyuedu.server.circle.MyCircleServer;
import com.wenyu.wenyuyuedu.utils.AbSharedUtil;
import com.wenyu.wenyuyuedu.utils.MyToast;
import com.wenyu.wenyuyuedu.utils.SharedConstants;
import com.wenyu.wenyuyuedu.utils.StatusBarUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/*书圈发现的详情页*/
public class CircleFindDetailActivity extends AppCompatActivity implements View.OnClickListener {

    @InjectView(R.id.header)
    ImageView header;
    @InjectView(R.id.tv_mycircle_titlecontent)
    TextView tvMycircleTitlecontent;
    @InjectView(R.id.my_detail_left)
    ImageView myDetailLeft;
    @InjectView(R.id.my_detail_title)
    TextView myDetailTitle;
    @InjectView(R.id.my_detail_right)
    ImageView myDetailRight;
    @InjectView(R.id.toolbar)
    Toolbar toolbar;
    @InjectView(R.id.collapse_toolbar)
    CollapsingToolbarLayout collapseToolbar;
    @InjectView(R.id.tab_help_title)
    TabLayout tabHelpTitle;
    @InjectView(R.id.vp_help_pager)
    ViewPager vpHelpPager;
    @InjectView(R.id.drawer_layout)
    CoordinatorLayout drawerLayout;
    @InjectView(R.id.circle_find_btn)
    Button circleFindBtn;
    @InjectView(R.id.circlr_conver)
    ImageView circlrConver;
    @InjectView(R.id.tv_biaoqian)
    TextView tvBiaoqian;
    @InjectView(R.id.tv_circle_type)
    TextView tvCircleType;
    @InjectView(R.id.tv_personage_cont)
    TextView tvPersonageCont;
    @InjectView(R.id.tv_personagecount)
    TextView tvPersonagecount;
    @InjectView(R.id.tv_content)
    TextView tv_content;
    private Intent intent;
    private String circle_find_titel;
    private String circle_find_cover;
    private String creatorName;
    private String circle_find_circletype;
    private String circle_find_collect_count;
    private String circle_find_content;
    private Activity activity;
    private String circle_find_id;
    private ViewPagerAdapter adapter;
    private TabLayout.Tab tabAt;
    private String login_find_uid;
    private TextView sun;
    private TextView sunT;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_circle_find_detail);
        ButterKnife.inject(this);
        StatusBarUtil.setStatusBar(CircleFindDetailActivity.this, R.color.white);
        activity = CircleFindDetailActivity.this;
        setupToolbar();
        initView();
        setupViewPager();
        requesDate();
    }

    private int page = 1;

    private void requesDate() {
        Intent getIntent = getIntent();
        Intent intent = new Intent();
        int circle_find_id = Integer.parseInt(getIntent.getStringExtra("circle_find_id"));
        String token = AbSharedUtil.getString(CircleFindDetailActivity.this, SharedConstants.USER_TOKEN);
        MyCircleServer myCircleServer = ApiWrapper.getInstance().create(MyCircleServer.class);
        Call<CircleDetailBean> circleDetail = myCircleServer.getCircleDetail(token, circle_find_id, 1, page);
        circleDetail.enqueue(new Callback<CircleDetailBean>() {
            @Override
            public void onResponse(Call<CircleDetailBean> call, Response<CircleDetailBean> response) {
                CircleDetailBean body = response.body();
                if (body != null) {
                    int code = body.getCode();
                    if (code == 1) {
                        String all_post = body.getInfo().getAll_post();
                        String all_high_post = body.getInfo().getAll_high_post();
                        String pubPath = body.getInfo().getPubPath();
                        Glide.with(CircleFindDetailActivity.this)
                                .load(pubPath)
                                .placeholder(R.drawable.login_logo)
                                .error(R.drawable.login_logo)
                                .into(circlrConver);
                        sun.setText(all_post);
                        sunT.setText(all_high_post);
                        tvCircleType.setText(body.getInfo().getTypeTitle());
                        tvPersonagecount.setText(body.getInfo().getCollecCount());
                        myDetailTitle.setText(body.getInfo().getPubTitle());
                        tvMycircleTitlecontent.setText(body.getInfo().getPubNickname());
                        tv_content.setText(body.getInfo().getPubContent());
                    } else if (code == 0) {
                        //token错误或失效
                        showLoginDoalog();
                    } else if (code == 3500) {
                        MyToast.showToast(CircleFindDetailActivity.this, "登陆后操作", Toast.LENGTH_SHORT);
                    }
                }
            }

            @Override
            public void onFailure(Call<CircleDetailBean> call, Throwable t) {

            }
        });
    }

    android.app.AlertDialog ad;
    private TextView quxiao;
    private TextView queding;

    /*显示登陆的dialog*/
    private void showLoginDoalog() {

        ad = new android.app.AlertDialog.Builder(CircleFindDetailActivity.this).create();
        ad.show();
        Window window = ad.getWindow();
        window.setContentView(R.layout.dailog_login);
        quxiao = (TextView) window.findViewById(R.id.dialog_login_quxiao);
        queding = (TextView) window.findViewById(R.id.dialog_login_queding);
        quxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ad.dismiss();
            }
        });
        queding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AbSharedUtil.putString(CircleFindDetailActivity.this, SharedConstants.USER_TOKEN, "");
                Intent intent = new Intent();
                intent.setClass(CircleFindDetailActivity.this, LoginActivity.class);
                startActivity(intent);
                CircleFindDetailActivity.this.finish();
                ad.dismiss();
            }
        });
    }

    /*初始化控件*/
    private void initView() {
        intent = getIntent();
        /*圈子的名字*/
        circle_find_titel = intent.getStringExtra("circle_find_titel");
        /*圈子的封面*/
        circle_find_cover = intent.getStringExtra("circle_find_cover");
        /*创建圈子的名称*/
        creatorName = intent.getStringExtra("creatorName");
         /*圈子的类名*/
        circle_find_circletype = intent.getStringExtra("circle_find_circletype");
          /*加入圈子的人数*/
        circle_find_collect_count = intent.getStringExtra("circle_find_collect_count");
        /*圈子的简介*/
        circle_find_content = intent.getStringExtra("circle_find_content");
        /*圈子的id*/
        circle_find_id = intent.getStringExtra("circle_find_id");
        /*当前登录用户的uid*/
        login_find_uid = intent.getStringExtra("login_find_uid");
        myDetailTitle.setText(circle_find_titel);
        if (creatorName != null) {
            tvMycircleTitlecontent.setText(creatorName);
        }

        if (circle_find_circletype != null) {
            tvCircleType.setText(circle_find_circletype);
        }

        if (circle_find_collect_count != null) {
            tvPersonagecount.setText(circle_find_collect_count);
        }
        if (circle_find_content != null) {
            tv_content.setText(circle_find_content);
        }
        circleFindBtn.setOnClickListener(this);
        myDetailLeft.setOnClickListener(this);
        vpHelpPager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                return true;
            }
        });
    }

    /*初始化toolbar*/
    private void setupToolbar() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setHomeButtonEnabled(false);
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
    }

    /*collapse_toolbar*/
    private void setCollapse() {
        CollapsingToolbarLayout viewById = (CollapsingToolbarLayout) findViewById(R.id.collapse_toolbar);
        viewById.setTitle("");

    }


    private static final String TAG = "CircleFindDetailActivit";

    private void setupViewPager() {
        final ViewPager viewPager = (ViewPager) findViewById(R.id.vp_help_pager);
        setupViewPager(viewPager);
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_help_title);
        tabLayout.setTabMode(TabLayout.MODE_FIXED);
        View inflate = View.inflate(activity, R.layout.tab_item_circlrdetail, null);
        sun = (TextView) inflate.findViewById(R.id.tab_sun);
        TextView name = (TextView) inflate.findViewById(R.id.tab_name);
        name.setText("全部");
        TabLayout.Tab a = tabLayout.newTab().setCustomView(inflate);
        tabLayout.addTab(a);
        View inflateT = View.inflate(activity, R.layout.tab_item_circlrdetail, null);
        sunT = (TextView) inflateT.findViewById(R.id.tab_sun);
        TextView nameT = (TextView) inflateT.findViewById(R.id.tab_name);
        nameT.setText("神贴");
        TabLayout.Tab aT = tabLayout.newTab().setCustomView(inflateT);
        tabLayout.addTab(aT);
        /*tablayout的监听*/
        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tab.getPosition();
                if (position == 1) {
                    MyToast.showToast(activity, "加入书圈后查看更多数据" + position, Toast.LENGTH_SHORT);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }


    private void setupViewPager(ViewPager viewPager) {
        adapter = new ViewPagerAdapter(getSupportFragmentManager(), activity);
        adapter.addFrag(new FindAll_Invitation_Fragment(), "全部");
        //   adapter.addFrag(new Find_Detity_Fregment(), "神贴");
        viewPager.setAdapter(adapter);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            /*返回*/
            case R.id.my_detail_left:
                finish();
                break;
            /*加入圈子的按钮*/
            case R.id.circle_find_btn:
                JoinCircle();
                break;
        }
    }

    /*加入圈子的钮*/
    private void JoinCircle() {
        String token = AbSharedUtil.getString(activity, SharedConstants.USER_TOKEN);
        JoinCircleServer joinCircleServer = ApiWrapper.getInstance().create(JoinCircleServer.class);
        Call<JoinCircleBean> joinBean = joinCircleServer.getJoinBean(token, Integer.parseInt(circle_find_id), 1, 1);
        joinBean.enqueue(new Callback<JoinCircleBean>() {
            @Override
            public void onResponse(Call<JoinCircleBean> call, Response<JoinCircleBean> response) {
                JoinCircleBean body = response.body();
                if (body != null) {
                    int code = body.getCode();
                    if (code == 1) {
                        intent.setClass(activity, Help_FeedBack_Activity.class);
                        intent.putExtra("creatorName", creatorName);
                        intent.putExtra("circleId", circle_find_id);
                        intent.putExtra("circleName", circle_find_titel);
                        intent.putExtra("circlecover", circle_find_cover);
                        intent.putExtra("login_find_uid", login_find_uid);
                        startActivity(intent);
                        finish();
                        MyToast.showToast(activity, "加入圈子成功", Toast.LENGTH_SHORT);
                    } else if (code == 0) {
                        MyToast.showToast(activity, "请登陆", Toast.LENGTH_SHORT);
                    } else if (code == 2500) {
                        MyToast.showToast(activity, "需要登陆后才可以操作", Toast.LENGTH_SHORT);
                    } else if (code == 2501) {
                        MyToast.showToast(activity, "不存在该书圈", Toast.LENGTH_SHORT);
                    } else if (code == 2502) {
                        MyToast.showToast(activity, "您已经收藏过了！", Toast.LENGTH_SHORT);
                    } else if (code == 2506) {
                        MyToast.showToast(activity, "抱歉您的账户被暂时限制了，无法进行此操作", Toast.LENGTH_SHORT);
                    } else if (code == 2507) {
                        MyToast.showToast(activity, "系统繁忙，请您稍后再试！", Toast.LENGTH_SHORT);
                    }
                }
            }

            @Override
            public void onFailure(Call<JoinCircleBean> call, Throwable t) {
                MyToast.showToast(activity, "系统繁忙，请您稍后再试！", Toast.LENGTH_SHORT);
            }
        });
    }

    static class ViewPagerAdapter extends FragmentPagerAdapter {

        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();
        private Context context;

        public ViewPagerAdapter(FragmentManager manager, Context context) {
            super(manager);
            this.context = context;

        }

        public View getTabView(int position) {
            View inflate = LayoutInflater.from(context).inflate(R.layout.circle_find_pager_item, null);
            TextView content = (TextView) inflate.findViewById(R.id.tv_viewpager_content);
            content.setText(mFragmentTitleList.get(position));
            return inflate;
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFrag(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }


    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

}
